﻿using Hzt_WebApi;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using WebHzt_Api.Models.Database;
using WebHzt_Api.service;

namespace WebHzt_Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BusinessController : Controller
    {
        private readonly Hzt_WebApiContext _db;
        private readonly IDatabase _redis;
        private readonly IMemoryCache cache;
        private readonly IVoteService _voteService;
        public BusinessController(Hzt_WebApiContext db, IVoteService voteService, RedisHelper client)
        {
            _redis = client.GetDatabase();
            _db = db;
            _voteService = voteService;
        }
        [HttpGet]
        public void SetRedisCache()
        {

            _redis.StringSet("RedisCache1", "6666");
        }
        /// <summary>
        /// 获取企业详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Datum GetDataInfo(int DataId)
        {
            var Data = _db.Data.FirstOrDefault(x => x.DataId == DataId);
            return Data;
        }
        /// <summary>
        /// 投票接口
        /// </summary>
        /// <param name="VoteId"></param>
        /// <returns></returns>
        //[HttpGet]
        //[Authorize]
        //public string AddVoteRedis(int VoteId)
        //{
        //    var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
        //    _voteService.AddVoteRedis(userId, VoteId);
        //    return "投票成功";

        //}
        [HttpGet]
        [Authorize]
        public string AddVoteRedis(int VoteId)
        {
            //添加商品进入购物车
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var hashKey = "vote_" + userId;
            //对购物车数量增加 如果哈希没有就添加后再加一
            _redis.HashIncrement(hashKey, VoteId);
            return "投票成功！"; 
        }
    }
}
